/**
 * @file     mergeTwoLists.js
 * @brief    [21. 合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/)
 * @author   Zhu
 * @date     2022-03-17 20:45
 */

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

/**
 * 虚拟头 + 迭代
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function (list1, list2) {
    let preHead = new ListNode();

    let prev = preHead;
    let cur1 = list1;
    let cur2 = list2;

    while (cur1 && cur2) {
        if (cur1.val <= cur2.val) {
            prev.next = cur1;
            cur1 = cur1.next;
        } else {
            prev.next = cur2;
            cur2 = cur2.next;
        }
        prev = prev.next;
    }

    prev.next = cur1 == null ? cur2 : cur1;

    return preHead.next; // 虚拟头
};

/**
 * 递归
 * @param {ListNode} list1
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeTwoLists = function (list1, list2) {
    if (list1 == null) return list2;
    if (list2 == null) return list1;
    if (list1.val <= list2.val) {
        list1.next = mergeTwoLists(list1.next, list2);
        return list1;
    } else {
        list2.next = mergeTwoLists(list2.next, list1);
        return list2;
    }
};
